<?php

namespace App\Service;

use App\Models\Doctor;
use App\User;

class Push
{
//腾讯的推送服务，安卓和ios两个端对应是两个应用，当后端推送时，无法知道用户是ios设备还是安卓设备，只能两端都发送一下
    private $android_access_id = "";
    private $android_secret_key = '';
    private $ios_access_id = '';
    private $ios_secret_key = '';
    private $url = 'https://api.tpns.sh.tencent.com/v3/push/app';

    public function __construct()
    {
        $this->android_access_id = config("omnipay.pushAndroid.AccessID");
        $this->android_secret_key = config("omnipay.pushAndroid.SecretKey");
        $this->ios_access_id = config("omnipay.pushIos.AccessID");
        $this->ios_secret_key = config("omnipay.pushIos.SecretKey");
    }


    //签名
    public function sign($body, $time, $type = 'android')
    {
        if ($type == 'android') {
            $str = $time . $this->android_access_id . $body;
            return base64_encode(hash_hmac('sha256', $str, $this->android_secret_key));
        } else {
            $str = $time . $this->ios_access_id . $body;
            return base64_encode(hash_hmac('sha256', $str, $this->ios_secret_key));
        }

    }

    /**
     * @param $user_id
     * @param $title
     * @param $content
     * @param array $params
     * @return bool|mixed
     * 发送消息至安卓设备
     */
    public function sendToAndroid($user, $title, $content, $params = [],$type =0)
    {
//        $user = User::find($user_id);
//        if (!$user || !$user->tpns_token) {
//            //获取用户推送的唯一标示
//            return false;
//        }
        if ($type == 1) {
            $tpns_token = $user;
        } else {
            $tpns_token = [$user->tpns_token];
        }
        $message = [
            'title' => $title,
            'content' => $content,
        ];
        if (count($params)) {
            $message['android']['custom_content'] = json_encode($params);
        }
        $data = [
            'audience_type' => 'token',
            'token_list' => $tpns_token,
            'message_type' => 'notify',
            'message' => $message,
        ];
        $time = time();
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $sign = $this->sign($data, $time, 'android');
        $header = [
            'AccessId:' . $this->android_access_id,
            'TimeStamp:' . $time,
            'Sign:' . $sign
        ];
        return $this->httpRequest($this->url, $data, false, $header);
    }

    /**
     * @param $user_id
     * @param $title
     * @param $content
     * @param array $params
     * @return bool|mixed
     * 发送推送至ios设备
     */
    public function sendToIos($user, $title, $content, $params = [],$type =0)
    {
//        $user = User::find($user_id);
//        if (!$user || !$user->tpns_token) {
//            return false;
//        }
        if ($type == 1) {
            $tpns_token = $user;
        } else {
            $tpns_token = [$user->tpns_token];
        }
        $message = [
            'title' => $title,
            'content' => $content,
            'ios' => [
                'aps' => [
                    'badge_type' => 1,
                ]
            ]
        ];
        if (count($params)) {
            $message['ios']['custom_content'] = json_encode($params);
        }
        $data = [
            'audience_type' => 'token',
            'token_list' =>$tpns_token,
            'message_type' => 'notify',
            'message' => $message,
            'environment' => 'dev'//product
        ];
        $time = time();
        $data = json_encode($data, JSON_UNESCAPED_UNICODE);
        $sign = $this->sign($data, $time, 'ios');
        $header = [
            'AccessId:' . $this->ios_access_id,
            'TimeStamp:' . $time,
            'Sign:' . $sign
        ];
        return $this->httpRequest($this->url, $data, false, $header);
    }


    public function httpRequest($url, $data, $yes = false, $headers)
    {
        $options = array(
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_HEADER => 0,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_POST => 1,
            CURLOPT_POSTFIELDS => $data,
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_TIMEOUT => 10000
        );
        $ch = curl_init();
        curl_setopt_array($ch, $options);
        $ret = curl_exec($ch);
        $error = curl_error($ch);
        $info = curl_getinfo($ch);
        curl_close($ch);
        if ($error != "") {
            throw new \Exception($error);
        }
        $code = $info["http_code"];
        if ($code != 200) {
            throw new \Exception("status: " . $code . ", message: " . $ret);
        }
        return json_decode($ret, 1);
    }



    /**
     * @param $param
     * @return \Illuminate\Http\JsonResponse
     */
    public function pushToUser($param)
    {
        if ($param['type'] == 1) { //用户
            $user = (new User())->where([['id', '=', $param['user_id']]])->first();
        } elseif ($param['type'] == 2) { //医生
            $user = (new Doctor())->where([['id', '=', $param['user_id']]])->first();
        }
        if (!empty($user->use_phone_type)) {
            if ($user->use_phone_type == 1) { //android
                if ($user->tpns_token) {
                    $res = self::sendToAndroid($user, $param['title'], $param['content'], []);
                }
            } else { //ios
                if ($user->tpns_token) {
                    $res = self::sendToIos($user, $param['title'], $param['content'], []);
                }
            }
            return $res;
        }
        return false;
    }




}


//$push = new \App\Utility\Push();
//$push->sendToIos($this->user_id,$this->title,$this->content,$this->params);
//$push->sendToAndroid($this->user_id,$this->title,$this->content,$this->params);
